package com.project.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration
@ComponentScan("com.project.service")
@ComponentScan("com.project.mapper")
@MapperScan("com.project.mapper")
@EnableTransactionManagement
public class MyBatisConfig {
    /***
     * 配置数据源
     * @return 数据源对象
     */
    @Bean
    public DataSource getSource(){
        DruidDataSource dataSource = new DruidDataSource();
        //配置连接
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        //配置sql
        dataSource.setUrl("jdbc:mysql://localhost:6789/ps?characterEncoding=utf-8&allowMultiQueries=true");
        //配置用户名
        dataSource.setUsername("root");
        //配置密码
        dataSource.setPassword("lovo");

        //配置连接池最大连接数为100
        dataSource.setMaxActive(100);
        //配置连接池最小连接数为20
        dataSource.setMinIdle(20);
        //配置超时时间
        dataSource.setMaxWait(1000);
        return dataSource;
    }

    /***
     *配置会话工厂
     * @return 会话工厂对象
     */
    @Bean
    public FactoryBean getFactoryBean(){
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        //配置数据源
        factoryBean.setDataSource(this.getSource());
        //配置mybatis主配置文件
        factoryBean.setConfigLocation(new ClassPathResource("mybatis.cfg.xml"));

        return factoryBean;
    }

    /***
     * 配置事务管理器
     * @return 事务管理器
     */
    @Bean
    public TransactionManager getManager(){
        DataSourceTransactionManager manager = new DataSourceTransactionManager();
        //配置数据源
        manager.setDataSource(this.getSource());
        return manager;
    }
}
